<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员分配 - 实验室辅助管理系统</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <link rel="stylesheet" th:href="@{/css/fontawesome-local.css}">
    <style>
        /* 消息提示样式 */
        .message-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            max-width: 400px;
        }

        .message {
            background: white;
            border-radius: 8px;
            padding: 16px 20px;
            margin-bottom: 10px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            border-left: 4px solid #67C23A;
            display: flex;
            align-items: center;
            gap: 12px;
            transform: translateX(100%);
            opacity: 0;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            animation: slideIn 0.3s ease-out forwards;
        }

        .message.success {
            border-left-color: #67C23A;
        }

        .message.error {
            border-left-color: #F56C6C;
        }

        .message.warning {
            border-left-color: #E6A23C;
        }

        .message.info {
            border-left-color: #409EFF;
        }

        .message-icon {
            font-size: 18px;
            flex-shrink: 0;
        }

        .message.success .message-icon {
            color: #67C23A;
        }

        .message.error .message-icon {
            color: #F56C6C;
        }

        .message.warning .message-icon {
            color: #E6A23C;
        }

        .message.info .message-icon {
            color: #409EFF;
        }

        .message-content {
            flex: 1;
            font-size: 14px;
            color: #303133;
            line-height: 1.4;
        }

        .message-close {
            font-size: 16px;
            color: #C0C4CC;
            cursor: pointer;
            flex-shrink: 0;
            transition: color 0.3s ease;
        }

        .message-close:hover {
            color: #909399;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }

        .message.hiding {
            animation: slideOut 0.3s ease-in forwards;
        }
    </style>
</head>
<body>
    <!-- 消息提示容器 -->
    <div class="message-container" id="messageContainer"></div>

    <div class="management-container">
        <!-- 侧边栏 -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <h2><i class="fas fa-user-cog"></i> 管理员分配</h2>
            </div>
            <ul class="nav-menu">
                <li><a th:href="@{/dashboard}"><i class="fas fa-tachometer-alt"></i> 系统仪表盘</a></li>
                <li><a th:href="@{/college-management}"><i class="fas fa-university"></i> 学院管理</a></li>
                <li><a th:href="@{/term-management}"><i class="fas fa-calendar-alt"></i> 学期管理</a></li>
                <li><a th:href="@{/laboratory-management}"><i class="fas fa-microscope"></i> 实验室管理</a></li>
                <li><a th:href="@{/user-management}"><i class="fas fa-users"></i> 用户管理</a></li>
                <li class="active"><a th:href="@{/assignment-management}"><i class="fas fa-user-cog"></i> 管理员分配</a></li>
            </ul>
        </nav>

        <!-- 主内容区 -->
        <main class="main-content">
            <!-- 顶部栏 -->
            <header class="top-bar">
                <div class="top-bar-left">
                    <h1>管理员分配</h1>
                </div>
                <div class="top-bar-right">
                    <div class="user-info">
                        <span th:text="${currentUser.name}">管理员</span>
                        <a th:href="@{/logout}" class="logout-btn">退出</a>
                    </div>
                </div>
            </header>

            <!-- 内容区域 -->
            <div class="content">
                <!-- 操作栏 -->
                <div class="action-bar">
                    <button class="btn btn-primary" onclick="showAssignModal()">
                        <i class="fas fa-plus"></i> 新增分配
                    </button>
                    <div class="search-box">
                        <input type="text" id="searchInput" placeholder="搜索实验室或管理员..." onkeyup="filterAssignments()">
                        <i class="fas fa-search"></i>
                    </div>
                </div>

                <!-- 分配概览卡片 -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-microscope"></i>
                        </div>
                        <div class="stat-info">
                            <h3 th:text="${laboratories.size()}">10</h3>
                            <p>总实验室数</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-user-tie"></i>
                        </div>
                        <div class="stat-info">
                            <h3 th:text="${users.size()}">5</h3>
                            <p>实验室管理员</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="assignedCount">0</h3>
                            <p>已分配实验室</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-exclamation-circle"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="unassignedCount">0</h3>
                            <p>未分配实验室</p>
                        </div>
                    </div>
                </div>

                <!-- 实验室分配列表 -->
                <div class="card">
                    <div class="card-header">
                        <h3>实验室分配情况</h3>
                        <span class="badge" th:text="${laboratories.size()} + ' 个实验室'">0 个实验室</span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table" id="assignmentTable">
                                <thead>
                                    <tr>
                                        <th>实验室ID</th>
                                        <th>实验室名称</th>
                                        <th>所属学院</th>
                                        <th>分配状态</th>
                                        <th>管理员</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr th:each="lab : ${laboratories}">
                                        <td th:text="${lab.id}">1</td>
                                        <td th:text="${lab.name}">计算机基础实验室</td>
                                        <td th:text="${lab.college.name}">计算机科学与技术学院</td>
                                        <td>
                                            <span th:if="${lab.managers != null and !lab.managers.isEmpty()}" 
                                                  class="badge badge-success">已分配</span>
                                            <span th:if="${lab.managers == null or lab.managers.isEmpty()}" 
                                                  class="badge badge-warning">未分配</span>
                                        </td>
                                        <td>
                                            <div th:if="${lab.managers != null and !lab.managers.isEmpty()}">
                                                <span th:each="manager, iterStat : ${lab.managers}">
                                                    <span th:text="${manager.name}">张老师</span>
                                                    <span th:if="${!iterStat.last}">, </span>
                                                </span>
                                            </div>
                                            <span th:if="${lab.managers == null or lab.managers.isEmpty()}" 
                                                  style="color: #999;">无</span>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-primary" 
                                                    th:data-id="${lab.id}" th:data-name="${lab.name}" 
                                                    onclick="assignManagerFromButton(this)">
                                                <i class="fas fa-user-plus"></i> 分配管理员
                                            </button>
                                            <button th:if="${lab.managers != null and !lab.managers.isEmpty()}"
                                                    class="btn btn-sm btn-warning" 
                                                    th:data-id="${lab.id}" onclick="removeManagerFromButton(this)">
                                                <i class="fas fa-user-minus"></i> 移除分配
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 分配管理员模态框 -->
    <div id="assignModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>分配管理员</h3>
                <span class="close" onclick="closeModal('assignModal')">&times;</span>
            </div>
            <div class="modal-body">
                <form id="assignForm">
                    <input type="hidden" id="labId" name="labId">
                    <div class="form-group">
                        <label>实验室名称</label>
                        <input type="text" id="labName" class="form-control" readonly>
                    </div>
                    <div class="form-group">
                        <label for="managerId">选择管理员</label>
                        <select id="managerId" name="managerId" class="form-control" required>
                            <option value="">请选择管理员</option>
                            <option th:each="user : ${users}" th:value="${user.id}" th:text="${user.name + ' (' + user.username + ')'}">张老师 (zhang_lab)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>管理员信息</label>
                        <div id="managerInfo" style="background: #f8f9fa; padding: 10px; border-radius: 4px; margin-top: 5px;">
                            <p style="margin: 0; color: #666;">请先选择管理员</p>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('assignModal')">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveAssignment()">确认分配</button>
            </div>
        </div>
    </div>

    <script th:src="@{/js/app.js}"></script>
    <script>
        // 管理员数据 - 从服务器端动态生成
        const managers = [];
        
        // 页面加载后从服务器获取管理员数据
        fetch('/api/managers')
            .then(response => response.json())
            .then(data => {
                managers.length = 0; // 清空数组
                managers.push(...data); // 添加新数据
            })
            .catch(error => {
                console.error('获取管理员数据失败:', error);
                // 使用默认数据
                managers.push({
                    id: 1,
                    name: '张老师',
                    username: 'zhang_lab',
                    college: '计算机科学与技术学院',
                    contactInfo: 'zhang@university.edu'
                });
            });

        // 页面加载时更新统计数据
        document.addEventListener('DOMContentLoaded', function() {
            updateStats();
        });

        // 更新统计数据
        function updateStats() {
            const rows = document.querySelectorAll('#assignmentTable tbody tr');
            let assignedCount = 0;
            let unassignedCount = 0;
            
            rows.forEach(row => {
                const statusBadge = row.querySelector('.badge');
                if (statusBadge.textContent.trim() === '已分配') {
                    assignedCount++;
                } else {
                    unassignedCount++;
                }
            });
            
            document.getElementById('assignedCount').textContent = assignedCount;
            document.getElementById('unassignedCount').textContent = unassignedCount;
        }

        // 显示分配模态框
        function assignManager(labId, labName) {
            document.getElementById('labId').value = labId;
            document.getElementById('labName').value = labName;
            document.getElementById('managerId').value = '';
            document.getElementById('managerInfo').innerHTML = '<p style="margin: 0; color: #666;">请先选择管理员</p>';
            document.getElementById('assignModal').style.display = 'block';
        }

        // 从按钮分配管理员
        function assignManagerFromButton(button) {
            const id = button.getAttribute('data-id');
            const name = button.getAttribute('data-name');
            assignManager(id, name);
        }
        
        // 显示新增分配模态框
        function showAssignModal() {
            // 检查是否有未分配的实验室
            const rows = document.querySelectorAll('#assignmentTable tbody tr');
            let hasUnassigned = false;
            
            rows.forEach(row => {
                const statusBadge = row.querySelector('.badge');
                if (statusBadge.textContent.trim() === '未分配') {
                    hasUnassigned = true;
                }
            });
            
            if (!hasUnassigned) {
                showMessage('所有实验室都已分配管理员', 'info');
                return;
            }
            
            // 清空表单并显示第一个未分配的实验室
            rows.forEach(row => {
                const statusBadge = row.querySelector('.badge');
                if (statusBadge.textContent.trim() === '未分配') {
                    const cells = row.getElementsByTagName('td');
                    const labId = cells[0].textContent;
                    const labName = cells[1].textContent;
                    assignManager(labId, labName);
                    return false; // 跳出循环
                }
            });
        }

        // 管理员选择变化时更新信息
        document.getElementById('managerId').addEventListener('change', function() {
            const managerId = this.value;
            const managerInfo = document.getElementById('managerInfo');
            
            if (managerId) {
                const manager = managers.find(m => m.id == managerId);
                if (manager) {
                    managerInfo.innerHTML = `
                        <p style="margin: 0 0 5px 0;"><strong>姓名：</strong>${manager.name}</p>
                        <p style="margin: 0 0 5px 0;"><strong>用户名：</strong>${manager.username}</p>
                        <p style="margin: 0 0 5px 0;"><strong>所属学院：</strong>${manager.college}</p>
                        <p style="margin: 0;"><strong>联系方式：</strong>${manager.contactInfo}</p>
                    `;
                }
            } else {
                managerInfo.innerHTML = '<p style="margin: 0; color: #666;">请先选择管理员</p>';
            }
        });

        // 保存分配
        function saveAssignment() {
            const labId = document.getElementById('labId').value;
            const managerId = document.getElementById('managerId').value;
            
            if (!managerId) {
                showMessage('请选择管理员', 'warning');
                return;
            }
            
            const formData = new FormData();
            formData.append('labId', labId);
            formData.append('managerId', managerId);
            
            fetch('/api/assignments', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    closeModal('assignModal');
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    showMessage('分配失败：' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('分配失败，请稍后重试', 'error');
            });
        }

        // 移除分配
        function removeManager(labId) {
            if (confirm('确定要移除该实验室的管理员分配吗？')) {
                fetch('/api/assignments/' + labId, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(data.message, 'success');
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    } else {
                        showMessage('移除失败：' + data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('移除失败，请稍后重试', 'error');
                });
            }
        }

        // 从按钮移除分配
        function removeManagerFromButton(button) {
            const id = button.getAttribute('data-id');
            removeManager(id);
        }

        // 搜索过滤
        function filterAssignments() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const table = document.getElementById('assignmentTable');
            const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
            
            for (let i = 0; i < rows.length; i++) {
                const labName = rows[i].getElementsByTagName('td')[1].textContent.toLowerCase();
                const collegeName = rows[i].getElementsByTagName('td')[2].textContent.toLowerCase();
                const managerName = rows[i].getElementsByTagName('td')[4].textContent.toLowerCase();
                
                if (labName.includes(searchTerm) || collegeName.includes(searchTerm) || managerName.includes(searchTerm)) {
                    rows[i].style.display = '';
                } else {
                    rows[i].style.display = 'none';
                }
            }
        }

        // 关闭模态框
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modals = document.getElementsByClassName('modal');
            for (let i = 0; i < modals.length; i++) {
                if (event.target == modals[i]) {
                    modals[i].style.display = 'none';
                }
            }
        }
        
        // 消息提示功能
        function showMessage(message, type = 'success', duration = 3000) {
            const container = document.getElementById('messageContainer');
            const messageEl = document.createElement('div');
            messageEl.className = `message ${type}`;
            
            let iconClass = '';
            switch (type) {
                case 'success':
                    iconClass = 'fas fa-check-circle';
                    break;
                case 'error':
                    iconClass = 'fas fa-times-circle';
                    break;
                case 'warning':
                    iconClass = 'fas fa-exclamation-triangle';
                    break;
                case 'info':
                    iconClass = 'fas fa-info-circle';
                    break;
                default:
                    iconClass = 'fas fa-check-circle';
            }
            
            messageEl.innerHTML = `
                <i class="message-icon ${iconClass}"></i>
                <div class="message-content">${message}</div>
                <i class="message-close fas fa-times"></i>
            `;
            
            container.appendChild(messageEl);
            
            // 点击关闭按钮
            messageEl.querySelector('.message-close').addEventListener('click', function() {
                hideMessage(messageEl);
            });
            
            // 自动关闭
            if (duration > 0) {
                setTimeout(() => {
                    hideMessage(messageEl);
                }, duration);
            }
        }
        
        function hideMessage(messageEl) {
            messageEl.classList.add('hiding');
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }
    </script>
</body>
</html> 